import React, { Component } from "react";
import { Form, Input, Button, message as antMsg } from "antd";
import { setCookie, getQueryString } from "@/utils";
import { login } from "@/api/account";

class Login extends Component{

    constructor() {
        super();
        this.state = {
            isDisabled: false
        }
    }

    render() {
        return (
            <div className="login central">
                <Form onFinish={this.finish}>
                    <Form.Item label="用户名：" name="account" rules={[{required: true,message: '请输入手机号/邮箱',}]}>
                        <Input placeholder="手机号/邮箱" />
                    </Form.Item>
                    <Form.Item label="密码：" name="password" rules={[{required: true,message: '请输入密码',}]}>
                        <Input.Password placeholder="密码" />
                    </Form.Item>
                    <Form.Item className="btn">
                        <Button type="primary" htmlType="submit" disabled={this.state.isDisabled}>登录</Button>
                        <a href="/">返回首页</a>
                    </Form.Item>
                </Form>
            </div>
        )
    }
    // 用户登录
    finish = (values) => {
        this.setState({
            isDisabled: true
        });
        login(this.qs.stringify({
            usertype: 0,
            client_id: 1,
            client_secret: 'server',
            grant_type: 'password',
            username: values.account,
            password: values.password,
        })).then(res => {
            const redirect = getQueryString('redirect');
            if(res && res.access_token){
                antMsg.success('登录成功');
                setCookie("USER_TOKEN", res.access_token, 1);
                setTimeout(() => {
                    this.props.history.push(redirect ? decodeURIComponent(redirect) : '/user')
                }, 500)
            }else{
                antMsg.warning('登录失败，请重试')
            }
        }).finally(() => {
            this.setState({
                isDisabled: false
            })
        })
    }

}

export default Login
